#include <pwd.h>
#include <string.h>
#include <stdio.h>
#include <regex.h>
#include <sys/stat.h>
#include <sys/types.h>
#include "debug.h"
#include "config.h"

/* --- private functions --- */

char * cfg_path() 
{
  static char config_path[255];
  char *config_dir;
  struct passwd *user_data;
 
  user_data = getpwuid(geteuid());
  config_dir = g_strdup_printf("%s/.%s", user_data->pw_dir, PACKAGE_NAME);

  mkdir(config_dir, 0750);
  g_sprintf(config_path, "%s/config", config_dir); 

  g_free(config_dir);
  return config_path;
}
		   


/* --- bodies of functions ---*/

void config_default(config_t *config) 
{
  struct passwd *user_data;
  user_data = getpwuid(geteuid());

  g_sprintf(config->library, "%s/Desktop/Records", user_data->pw_dir);
  strcpy(config->video_device, "/dev/video");
  strcpy(config->audio_device, "plughw:0,0");
  strcpy(config->audio_input, "aux");
  config->channels = NULL;
}

int config_read(config_t *config) 
{
  DEBUG_ENTER("config_read");
  char *path;
  regex_t regline;
  FILE *cfgfile;

  path = cfg_path();
  cfgfile = fopen(path,"r+");
  if (cfgfile == NULL)
    return ERR_OPEN;

  regcomp(&regline, "\\(\\S*\\)\\s*=\\s*\\(\\S*\\)", 0);
  while(!feof(cfgfile)) {
    char line[255];

    if (fgets(line,255,cfgfile) != NULL) {
      gchar *arg, *param;
      regmatch_t pmatch[3];

      if (regexec(&regline, line, 3, pmatch, 0) != 0) {
	regfree(&regline);
	fclose(cfgfile);
	return ERR_CONFIG;
      }

      arg = g_strndup(line+pmatch[1].rm_so, pmatch[1].rm_eo - pmatch[1].rm_so);
      param = g_strndup(line+pmatch[2].rm_so, pmatch[2].rm_eo - pmatch[2].rm_so);

      if (!strcmp(arg,"video_device"))
	g_strlcpy(config->video_device, param, 255);
      if (!strcmp(arg,"audio_device"))
	g_strlcpy(config->audio_device, param, 255);
      if (!strcmp(arg,"audio_input"))
	g_strlcpy(config->audio_input, param, 255);
      if (!strcmp(arg,"library"))
	g_strlcpy(config->library, param, 255);

      g_free(arg);
      g_free(param);
    }
  }
  regfree(&regline);
  fclose(cfgfile);
  return 0;
  
}

int config_save(config_t *config) 
{
  char *path = cfg_path();
  FILE *cfgfile = fopen(path,"w+");
  if (cfgfile == NULL)
    return ERR_OPEN;

  fprintf(cfgfile, "video_device = %s\n", config->video_device);
  fprintf(cfgfile, "audio_device = %s\n", config->audio_device);
  fprintf(cfgfile, "audio_input = %s\n", config->audio_input);
  fprintf(cfgfile, "library = %s\n", config->library);
  fclose(cfgfile);
  return 0;
}

void config_release(config_t *config) 
{
}
